# Create your views here.

from django.views import View

from model.models import Point
from server.utils import Response, LoginRequiredPerson, Verify, Code, Request, Calculate_coordinates


class PointShareView(LoginRequiredPerson, View):
    """ User operation points share """

    def get(self, request):
        """ Search for shared points near the location """
        try:
            longitude = float(request.GET.get('longitude'))
            latitude = float(request.GET.get('latitude'))
            distance = float(request.GET.get('distance', 10000))
        except Exception as e:
            return Response.Json(code=Code.BadRequest)

        lon_min, lon_max, lat_min, lat_max = Calculate_coordinates(longitude, latitude, distance)

        points = Point.objects.filter(type=Point.Type.share,
                                      longitude__range=[lon_min, lon_max],
                                      latitude__range=[lat_min, lat_max]
                                      )
        points = [point.info() for point in points]
        return Response.Json(points=points)

    @Request.getJson
    def post(self, request):
        """ Set an existing point as shared """
        pid = request.JSON.get('pid')

        for code in [Verify.pointPid(pid)]:
            if code != Code.OK:
                return Response.Json(code=code)

        point = Point.objects.get(pid=pid)
        if point.uploader != request.user:
            return Response.Json(code=Code.Error, msg="You don't have permission to set someone else's points")

        if point.type == Point.Type.share:
            return Response.Json(code=Code.Error, msg="This point is already a shared point")
        elif point.status == Point.Status.applying:
            return Response.Json(code=Code.Error, msg="This point is currently applying for sharing")

        point.set_status(Point.Status.applying)
        return Response.Json()
